from flask import Blueprint, render_template, request, redirect, url_for, session, flash, jsonify, make_response
from models import CardModel, TradeModel, UserModel, db
import csv
from io import StringIO
from datetime import datetime

client_bp = Blueprint('client', __name__, url_prefix='/client')


@client_bp.route('/clientmain')
def clientmain():
    if 'cardID' not in session or session.get('is_admin'):
        flash('请先登录', 'error')
        return redirect(url_for('auth.login'))

    card = CardModel.query.filter_by(cardID=session['cardID']).first()
    if not card:
        flash('银行卡信息错误', 'error')
        return redirect(url_for('auth.logout'))

    user = UserModel.query.filter_by(customerID=card.customerID).first()
    if not user:
        flash('用户信息不存在', 'error')
        return redirect(url_for('auth.logout'))

    return render_template('clientmain.html',
                           card=card,
                           user=user,
                           balance=card.balance)


@client_bp.route('/deposit', methods=['POST'])
def deposit():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        amount = float(request.form.get('amount'))
        remark = request.form.get('remark', '存款')

        if amount <= 0:
            return jsonify({'success': False, 'message': '金额必须大于0'})

        # 创建交易记录
        trade = TradeModel(
            cardID=card_id,
            tradeType='存款',
            tradeMoney=amount,
            remark=remark
        )
        db.session.add(trade)
        db.session.commit()

        # 触发器会自动更新余额
        return jsonify({'success': True, 'message': '存款成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'存款失败: {str(e)}'})


@client_bp.route('/withdraw', methods=['POST'])
def withdraw():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        amount = float(request.form.get('amount'))
        remark = request.form.get('remark', '取款')

        if amount <= 0:
            return jsonify({'success': False, 'message': '金额必须大于0'})

        card = CardModel.query.get(card_id)
        if card.balance < amount:
            return jsonify({'success': False, 'message': '余额不足'})

        # 创建交易记录
        trade = TradeModel(
            cardID=card_id,
            tradeType='取款',
            tradeMoney=amount,
            remark=remark
        )
        db.session.add(trade)
        db.session.commit()

        return jsonify({'success': True, 'message': '取款成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'取款失败: {str(e)}'})


@client_bp.route('/transfer', methods=['POST'])
def transfer():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        to_card_id = request.form.get('toCardID')
        amount = float(request.form.get('amount'))
        remark = request.form.get('remark', '转账')

        if amount <= 0:
            return jsonify({'success': False, 'message': '金额必须大于0'})

        # 检查目标卡是否存在
        to_card = CardModel.query.get(to_card_id)
        if not to_card:
            return jsonify({'success': False, 'message': '目标银行卡不存在'})

        # 调用存储过程执行转账
        db.session.execute(
            'CALL TransferFunds(:fromCard, :toCard, :amount, :remark)',
            {
                'fromCard': card_id,
                'toCard': to_card_id,
                'amount': amount,
                'remark': remark
            }
        )
        db.session.commit()

        return jsonify({'success': True, 'message': '转账成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'转账失败: {str(e)}'})


@client_bp.route('/report_loss', methods=['POST'])
def report_loss():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        card = CardModel.query.get(card_id)
        card.IsReportLoss = '是'
        db.session.commit()
        return jsonify({'success': True, 'message': '挂失成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'挂失失败: {str(e)}'})


@client_bp.route('/change_password', methods=['POST'])
def change_password():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    try:
        old_password = request.form.get('oldPassword')
        new_password = request.form.get('newPassword')

        card = CardModel.query.get(card_id)
        if card.passwd != old_password:
            return jsonify({'success': False, 'message': '原密码错误'})

        card.passwd = new_password
        db.session.commit()
        return jsonify({'success': True, 'message': '密码修改成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'密码修改失败: {str(e)}'})


@client_bp.route('/transactions')
def get_transactions():
    card_id = session.get('cardID')
    if not card_id:
        return jsonify({'success': False, 'message': '请先登录'})

    transactions = TradeModel.query.filter_by(cardID=card_id).order_by(TradeModel.tradeDate.desc()).all()
    return jsonify({
        'success': True,
        'data': [{
            'id': t.tradeID,
            'date': t.tradeDate.strftime('%Y-%m-%d %H:%M:%S'),
            'type': t.tradeType,
            'amount': float(t.tradeMoney),
            'remark': t.remark
        } for t in transactions]
    })


@client_bp.route('/export_transactions')
def export_transactions():
    card_id = session.get('cardID')
    if not card_id:
        flash('请先登录', 'error')
        return redirect(url_for('auth.login'))

    transactions = TradeModel.query.filter_by(cardID=card_id).order_by(TradeModel.tradeDate.desc()).all()

    # 创建CSV文件
    si = StringIO()
    cw = csv.writer(si)
    cw.writerow(['交易ID', '交易时间', '交易类型', '交易金额', '备注'])

    for t in transactions:
        cw.writerow([
            t.tradeID,
            t.tradeDate.strftime('%Y-%m-%d %H:%M:%S'),
            t.tradeType,
            t.tradeMoney,
            t.remark
        ])

    # 构建响应
    response = make_response(si.getvalue())
    response.headers[
        'Content-Disposition'] = f'attachment; filename=transactions_{card_id}_{datetime.now().strftime("%Y%m%d")}.csv'
    response.headers['Content-type'] = 'text/csv'
    return response